//
//  WXDelegate.swift
//  XuYiLobster
//
//  Created by 宋海胜 on 2020/11/2.
//  Copyright © 2020 叁拾叁. All rights reserved.
//

import UIKit
import Toast

class WXDelegate: NSObject, WXApiDelegate {
    
    var currentVC: HSWebViewController!
    //  微信回调
    func onResp(_ resp: BaseResp) {
        
        print(resp.errCode)

        // 1.分享后回调类
        if resp.isKind(of: SendMessageToWXResp.self) {
            // 2018年后不在返回分享成功或者失败 https://www.jianshu.com/p/a5166a4adecb
            if resp.errCode == 0 {
                print("分享成功")
                currentVC.view.makeToast("分享成功")
            } else {
                print("分享失败")
                currentVC.view.makeToast("分享失败")
            }
        }
        // 2.微信登录向微信请求授权回调类
        if resp.isKind(of: SendAuthResp.self) {
            if resp.errCode == 0 {
                print("登录成功")
                currentVC.view.makeToast("登录成功")
            } else {
                print("登录失败")
                currentVC.view.makeToast("登录失败")
            }
        }
        // 3.微信支付回调
        if resp.isKind(of: PayResp.self)
        {
            print("retcode = \(resp.errCode), retstr = \(resp.errStr)")
            switch resp.errCode
            {
            //  支付成功
            case 0 :
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: "WXPaySuccessNotification"), object: nil)
                toPayResultPage()
            case -2 :
                print("取消")
            //  支付失败
            default:
                self.WXPayFail()
                toPayResultPage()
                print("失败")
            }
        }
        //  微信登录回调
        if resp.errCode == 0 && resp.type == 0{//授权成功
            if let response = resp as? SendAuthResp {
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: "WXLoginSuccessNotification"), object: response.code)
            }
        }
    }
    
    func toPayResultPage() {
        currentVC.payResult()
    }
    
    func WXPayFail() {
        print("微信支付失败")
        currentVC.view.makeToast("分享失败")
    }
}
